package com.yuexun.dhdoctor.widget;

import android.app.Dialog;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.TextView;


import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.baselistener.OnRecorderListener;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.email.bean.MailFileDataBean;
import com.yuexun.dhdoctor.module.email.bean.UploadBean;
import com.yuexun.dhdoctor.module.email.model.impl.UploadModel;
import com.yuexun.dhdoctor.module.email.presenter.IUploadPresenter;
import com.yuexun.dhdoctor.module.email.presenter.impl.UploadPresenter;
import com.yuexun.dhdoctor.module.email.ui.view.IUploadView;
import com.yuexun.dhdoctor.util.EnvironmentShare;

import org.kymjs.kjframe.ui.ViewInject;

import java.io.File;
import java.io.IOException;

/**
 * Created by Administrator on 2017/3/8 0008.
 */

public class VoiceDialog extends Dialog implements View.OnClickListener, IUploadView {
    private Chronometer timer;
    private TextView cancel;
    private TextView uploading;
    private TextView hint;
    private ImageView voiceBt;
    private ImageView wave_icon;

    private MediaRecorder mediaRecorder;
    private boolean isSDCardExit; // 判断SDCard是否存在
    private File tempFile;
    private File audioRecord;
    private boolean isStart; //判断录音是否开始
    public OnRecorderListener listener;

    IUploadPresenter presenter_upload;
    int miss=0;
    int i=0;
    Thread thread;
    Handler handler =new Handler(){// 创建一个handler对象 ，用于监听子线程发送的消息
        public void handleMessage(Message msg)//接收消息的方法
        {
            int str = (int)msg.obj;//类型转化
            if(str == 0){
                wave_icon.setImageResource(R.drawable.wave_small);
            }else if(str == 1){
                wave_icon.setImageResource(R.drawable.wave_little);
            }else{
                wave_icon.setImageResource(R.drawable.wave_strong);
            }
        }
    };

    public void setListener(OnRecorderListener listener){
        this.listener = listener;
    }

    public VoiceDialog(Context context) {
        super(context, R.style.loadingDialogStyle);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_voice);
        timer = (Chronometer) this.findViewById(R.id.timer);
        cancel = (TextView) this.findViewById(R.id.cancel_bt);
        uploading = (TextView) this.findViewById(R.id.uploading_bt);
        hint = (TextView) this.findViewById(R.id.hint);
        voiceBt = (ImageView) this.findViewById(R.id.voice_bt);
        wave_icon = (ImageView) this.findViewById(R.id.ic_wave_icon);

        isStart = false;
        presenter_upload = new UploadPresenter(new UploadModel(),this);
        isSDCardExit = EnvironmentShare.haveSdCard();

        cancel.setOnClickListener(this);
        uploading.setOnClickListener(this);
        voiceBt.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.cancel_bt:
                dismiss();
                break;
            case R.id.uploading_bt:
                if(tempFile != null){
                    uploading.setEnabled(false);
                    upload(tempFile);
                }else {
                    ViewInject.toast("请先录音...");
                }
                break;
            case R.id.voice_bt:
                if(isStart){
                    initStop();
                }else{
                    if(isSDCardExit){
                        voiceBt.setImageResource(R.drawable.voice_stop_bt);
                        audioRecord = EnvironmentShare.getAudioRecordDir();
                        initRecorder();
                        startRecorder();
                        hint.setText("正在录音");
                        hint.setTextColor(0xff969696);
                        uploading.setTextColor(0xffacacac);
                        uploading.setEnabled(false);
                        timer.setBase(SystemClock.elapsedRealtime());//计时器清零
                        timer.start();
                        timer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {

                            @Override
                            public void onChronometerTick(Chronometer ch) {
                                miss++;
                                if(miss == 60){
                                    initStop();
                                }else if(miss > 49){
                                    hint.setText((59-miss) +"");
                                }
                            }
                        });
                        isStart = !isStart;
                    }else{
                        ViewInject.toast("请插入SD卡");
                    }
                }
                break;
        }
    }

    private void initStop(){
        hint.setText("录音结束，请上传");
        handler.removeCallbacks(thread);
        wave_icon.setImageResource(R.drawable.wave_little);
        voiceBt.setImageResource(R.drawable.voice_start_bt);
        stopRecorder();
        uploading.setTextColor(0xff207ae1);
        uploading.setEnabled(true);
        timer.stop();
        isStart = !isStart;
    }

    /**
     * 准备录音
     */
    private void initRecorder(){
        mediaRecorder = new MediaRecorder();

        // 设置音频来源(一般为麦克风)
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        // 设置音频输出格式（默认的输出格式）
//            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
        // 设置音频编码方式（默认的编码方式）
//            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        // 创建一个临时的音频输出文件.record_是文件的前缀名 .amr是后缀名
        try {
            tempFile = File.createTempFile("record_", ".mp3", audioRecord);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 设置录制器的文件保留路径
        mediaRecorder.setOutputFile(tempFile.getAbsolutePath());
    }

    /**
     * 开始录音
     */
    private void startRecorder(){
        threadStart();
        try {
            mediaRecorder.prepare();
            mediaRecorder.start();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止录音
     */
    private void stopRecorder(){
        if (mediaRecorder != null && tempFile != null && tempFile.exists()) {
            mediaRecorder.stop();
            mediaRecorder.reset();// 释放资源
            mediaRecorder = null;
        }
    }

    private void threadStart(){
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                if(i >= 2){
                    i = 0;
                }else{
                    i++;
                }
                handler.postDelayed(thread,500);
                Message msg = new Message();//创建消息类
                msg.obj=i;//消息类对象中存入消息
                handler.sendMessage(msg);//通过handler对象发送消息
            }
        });
        thread.start();
    }

    private void playRecorder() {
        if (mediaRecorder != null) {
            mediaRecorder.stop();
            mediaRecorder.reset();
        }

        if (tempFile != null && tempFile.exists()) {
            Log.i("com.kingtone.www.record", ">>>>>>>>>" + tempFile);
            MediaPlayer mediaPlayer = new MediaPlayer();
            // 为播放器设置数据文件
            try {
                mediaPlayer.setDataSource(tempFile.getAbsolutePath());
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 准备并且启动播放器
            try {
                mediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mediaPlayer.start();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    setTitle("录音播放完毕.");
                }
            });

        }
    }

    /**
     * 上传文件
     * @param file 需要上传的文件
     * @return 上传是否成功
     */
    private void upload(final File file){
        Log.i("tempFile：" , file.toString());
        Log.i("tempFile.getName():", file.getName());

        presenter_upload.uploadFile(file.toString());
    }

    @Override
    public void uploadDialogStatus(int status) {
        switch (status) {
            case AppConfig.SHOW_DIALOG:
                uploading.setText("正在上传...");
                break;
            case AppConfig.DISMISS_DIALOG:
                ViewInject.toast("录音文件上传成功！");
                break;

        }

    }

    @Override
    public void updateFile(UploadBean uploadBean) {
        MailFileDataBean mailFileDataBean = uploadBean.getData().get(0);
        if(listener != null){
            listener.onRecorder(tempFile, mailFileDataBean.getFileUuid());
        }
        dismiss();
    }
}
